package com.yiqingjing.utils;

import java.util.ArrayList;
import java.util.Calendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.os.Parcelable;

import com.yiqingjing.model.Sence;
import com.yiqingjing.nextset.GetLocation;

public class ApplaySetting {
	
	private Context context;
	private WifiReceiver receiver = new WifiReceiver();
	private double latitude;
	private double longitude;
	private int hour;
	private int minute;
	
	public ApplaySetting(Context context){
		this.context = context;
	}
	
	public void setMode(int mode, final Sence sence){
		switch(mode){
		case 1:
			IntentFilter filter = new IntentFilter();
			filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
			filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
			filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
			context.registerReceiver(receiver, filter);
			break;
		case 2:
			context.unregisterReceiver(receiver);
			latitude = sence.getLatitude();
			longitude = sence.getLongitude();
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					ArrayList<Double> result = GetLocation.getCurrentLocation(context);
					if(result.get(0) == latitude && result.get(1) == longitude){
						applay(sence);
					}
					try{
						Thread.sleep(2000);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			});
			break;
		case 3:
			context.unregisterReceiver(receiver);
			hour = sence.getHour();
			minute = sence.getMinute();
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					Calendar calendar = Calendar.getInstance();
					if(calendar.get(Calendar.HOUR) == hour && 
							calendar.get(Calendar.MILLISECOND) == minute){
						applay(sence);
					}
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
				}
			});
			break;
		}
	}
	
	public void applay(Sence sence){
		ChangeMode.setMode(context, sence.getAlarm(), sence.getMedia(), sence.getRing(),
				sence.getRingmode(), sence.getLightmode(), sence.getLightness(),
				sence.getAuto_rotate(), sence.getWifi(), sence.getGprs(), 
				sence.getWifihot(), sence.getGps(), sence.getBluetooth(), sence.getRingUri());
	}
	
	public class WifiReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(arg1.getAction())){
				Parcelable parcelable = arg1.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
				if(null != parcelable){
					NetworkInfo info = (NetworkInfo) parcelable;
					State state = info.getState();
					boolean isConnected = state == State.CONNECTED;
					if(isConnected){
						
					}
				}
			}
		}	
	}
	
}
